<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="140px">
      <el-form-item label="高校名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入高校名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="所属区域" prop="regionId">
        <el-cascader
          v-model="queryParams.regionId"
          :options="regionOptions"
          :props="cascaderProps"
          clearable
          placeholder="请选择所属区域"
          @change="handleRegionChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['race:university:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['race:university:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['race:university:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" align="center" width="80" />
      <el-table-column label="高校名称" prop="name" align="center" />
      <el-table-column label="所属区域" align="center" width="300">
        <template #default="scope">
          <span v-if="scope.row.region">
            {{ scope.row.region.province }} - {{ scope.row.region.city }} - {{ scope.row.region.district }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['race:university:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['race:university:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="高校名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入高校名称" />
        </el-form-item>
        <el-form-item label="所属区域" prop="regionId">
          <el-cascader
            v-model="form.regionId"
            :options="regionOptions"
            :props="cascaderProps"
            placeholder="请选择所属区域"
            @change="handleFormRegionChange"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from 'vue'
import { listUniversity, getUniversity, addUniversity, updateUniversity, delUniversity } from '@/api/race/university'
import { listRegion } from '@/api/race/region'

const { proxy } = getCurrentInstance()

const list = ref([])
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const open = ref(false)
const title = ref('')
const ids = ref([])
const single = ref(true)
const multiple = ref(true)

// 地区选项
const regionOptions = ref([])
const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  emitPath: false,
  checkStrictly: true
}

const data = reactive({
  form: {
    id: undefined,
    name: undefined,
    regionId: undefined
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    regionId: undefined
  },
  rules: {
    name: [{ required: true, message: '高校名称不能为空', trigger: 'blur' }],
    regionId: [{ required: true, message: '请选择所属区域', trigger: 'change' }]
  }
})

const { form, queryParams, rules } = toRefs(data)

function getList() {
  loading.value = true
  listUniversity(queryParams.value).then(res => {
    list.value = res.rows
    total.value = res.total
    loading.value = false
  })
}

function cancel() {
  open.value = false
  reset()
}

function reset() {
  form.value = {
    id: undefined,
    name: undefined,
    regionId: undefined
  }
  proxy.resetForm('formRef')
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  proxy.resetForm('queryRef')
  queryParams.value.name = undefined
  queryParams.value.regionId = undefined
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

function handleAdd() {
  reset()
  open.value = true
  title.value = '新增高校'
}

function handleUpdate(row) {
  reset()
  const id = row.id || ids.value[0]
  getUniversity(id).then(res => {
    form.value = res.data
    open.value = true
    title.value = '修改高校'
  })
}

function submitForm() {
  proxy.$refs['formRef'].validate(valid => {
    if (!valid) return
    const req = form.value.id ? updateUniversity(form.value) : addUniversity(form.value)
    req.then(() => {
      proxy.$modal.msgSuccess(form.value.id ? '修改成功' : '新增成功')
      open.value = false
      getList()
    })
  })
}

function handleDelete(row) {
  const delIds = row.id ? [row.id] : ids.value
  proxy.$modal.confirm('是否确认删除编号为"' + delIds.join(',') + '"的数据项？').then(() => {
    return delUniversity(delIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => {})
}

// 地区变化处理
function handleRegionChange(value) {
  // value 是选中的地区ID
  queryParams.value.regionId = value
}

function handleFormRegionChange(value) {
  // value 是选中的地区ID
  form.value.regionId = value
}

// 加载地区数据
async function loadRegionOptions() {
  try {
    console.log('开始加载地区数据...')
    
    // 使用API接口获取所有地区数据
    const res = await listRegion({ pageNum: 1, pageSize: 10000 })
    console.log('API响应:', res)
    
    const regions = res.rows
    console.log('地区数据:', regions)
    console.log('地区数据数量:', regions ? regions.length : 0)
    
    if (!regions || regions.length === 0) {
      console.warn('没有找到地区数据，可能需要先导入地区数据到数据库')
      // 显示一个简单的测试数据
      regionOptions.value = [{
        value: 'test',
        label: '测试地区',
        children: [{
          value: 'test-city',
          label: '测试市',
          children: [{
            value: 999,
            label: '测试县/区'
          }]
        }]
      }]
      return
    }
    
    const regionMap = new Map()
    
    // 构建树形结构
    regions.forEach(region => {
      const provinceKey = region.province
      const cityKey = `${region.province}-${region.city}`
      
      // 省份
      if (!regionMap.has(provinceKey)) {
        regionMap.set(provinceKey, {
          value: provinceKey,
          label: region.province,
          children: []
        })
      }
      
      // 市
      const province = regionMap.get(provinceKey)
      const cityExists = province.children.find(city => city.value === cityKey)
      if (!cityExists) {
        province.children.push({
          value: cityKey,
          label: region.city,
          children: []
        })
      }
      
      // 县/区
      const city = province.children.find(city => city.value === cityKey)
      city.children.push({
        value: region.id,
        label: region.district
      })
    })
    
    console.log('构建的地区选项:', Array.from(regionMap.values()))
    regionOptions.value = Array.from(regionMap.values())
  } catch (error) {
    console.error('加载地区数据失败:', error)
    // 显示错误信息
    regionOptions.value = [{
      value: 'error',
      label: '加载失败',
      children: []
    }]
  }
}

onMounted(() => {
  loadRegionOptions()
  getList()
})
</script>
